<template>
  <view class="test-container">
    <view class="test-header">
      <text class="title">前后端交互测试</text>
    </view>

    <view class="test-section">
      <text class="section-title">连接状态</text>
      <view class="status-item">
        <text class="status-label">后端API:</text>
        <text
          class="status-value"
          :class="{ success: apiStatus, error: !apiStatus }"
        >
          {{ apiStatus ? "连接正常" : "连接失败" }}
        </text>
      </view>
      <view class="status-item">
        <text class="status-label">WebSocket:</text>
        <text
          class="status-value"
          :class="{ success: wsStatus, error: !wsStatus }"
        >
          {{ wsStatus ? "连接正常" : "连接失败" }}
        </text>
      </view>
    </view>

    <view class="test-section">
      <text class="section-title">基础API测试</text>
      <button @click="testUserList" class="test-btn">测试获取用户列表</button>
      <button @click="testRegister" class="test-btn">测试用户注册</button>
      <button @click="testLogin" class="test-btn">测试用户登录</button>
      <button @click="testWebSocket" class="test-btn">测试WebSocket</button>
    </view>

    <view class="test-section">
      <text class="section-title">好友管理测试</text>
      <button @click="testFriendAPI" class="test-btn">测试好友管理API</button>
      <button @click="testSearchUsers" class="test-btn">测试搜索用户</button>
      <button @click="testFriendRequest" class="test-btn">测试好友申请</button>
    </view>

    <view class="test-section">
      <text class="section-title">测试结果</text>
      <scroll-view class="log-container" scroll-y>
        <view v-for="(log, index) in logs" :key="index" class="log-item">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-message" :class="log.type">{{ log.message }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { 
  getUserList, 
  login, 
  register, 
  getFriendList,
  searchUsers,
  getReceivedFriendRequests,
  sendFriendRequest
} from "@/utils/api.js";
import { connectWebSocket, closeWebSocket } from "@/utils/websocket.js";

export default {
  data() {
    return {
      apiStatus: false,
      wsStatus: false,
      logs: [],
    };
  },

  onLoad() {
    this.addLog("测试页面加载完成", "info");
          this.addLog("主要API地址: http://localhost:8080/api", "info");
      this.addLog("认证API地址: http://localhost:8083/login", "info");
            this.addLog("WebSocket地址: ws://localhost:9999/ws", "info");
  },

  methods: {
    addLog(message, type = "info") {
      const now = new Date();
      const time = now.toLocaleTimeString();
      this.logs.unshift({
        time,
        message,
        type,
      });

      if (this.logs.length > 50) {
        this.logs = this.logs.slice(0, 50);
      }
    },

    async testUserList() {
      this.addLog("开始测试获取用户列表...", "info");

      try {
        const result = await getUserList();
        if (result.code === 200) {
          this.apiStatus = true;
          this.addLog("✅ 获取用户列表成功", "success");
          this.addLog(`用户数量: ${result.data.length}`, "info");
          result.data.forEach((user) => {
            this.addLog(`用户: ${user.username} (${user.nickname})`, "info");
          });
        } else {
          this.addLog(`❌ 获取用户列表失败: ${result.message}`, "error");
        }
      } catch (error) {
        this.apiStatus = false;
        this.addLog(`❌ 获取用户列表失败: ${error.message}`, "error");
      }
    },



    async testRegister() {
      this.addLog("开始测试用户注册...", "info");

      const randomSuffix = Math.floor(Math.random() * 10000);
      const testUser = {
        username: `test${randomSuffix}`,
        password: "test123",
        nickname: `测试用户${randomSuffix}`,
      };

      try {
        const result = await register(testUser);
        if (result.code === 200) {
          this.addLog("✅ 用户注册成功", "success");
          this.addLog(`用户: ${testUser.username}`, "info");
          this.addLog(
            `Token: ${result.data.token.substring(0, 20)}...`,
            "info"
          );
        } else {
          this.addLog(`❌ 用户注册失败: ${result.message}`, "error");
        }
      } catch (error) {
        this.addLog(`❌ 用户注册失败: ${error.message}`, "error");
      }
    },

    async testLogin() {
      this.addLog("开始测试用户登录...", "info");

      try {
        const result = await login({
          username: "test",
          password: "test123",
        });

        if (result.code === 200) {
          this.addLog("✅ 用户登录成功", "success");
          this.addLog(`用户: ${result.data.user.username}`, "info");
          this.addLog(
            `Token: ${result.data.token.substring(0, 20)}...`,
            "info"
          );
        } else {
          this.addLog(`❌ 用户登录失败: ${result.message}`, "error");
        }
      } catch (error) {
        this.addLog(`❌ 用户登录失败: ${error.message}`, "error");
      }
    },

    testWebSocket() {
      this.addLog("开始测试WebSocket连接...", "info");

      const token = uni.getStorageSync("token") || "test-token";

      try {
        connectWebSocket(token, (message) => {
          this.addLog(
            `📨 收到WebSocket消息: ${JSON.stringify(message)}`,
            "success"
          );
        });

        setTimeout(() => {
          this.wsStatus = true;
          this.addLog("✅ WebSocket连接成功", "success");
        }, 2000);
      } catch (error) {
        this.wsStatus = false;
        this.addLog(`❌ WebSocket连接失败: ${error.message}`, "error");
      }
    },

    async testFriendAPI() {
      this.addLog("开始测试好友管理API...", "info");

      try {
        // 测试获取好友列表
        const friendResult = await getFriendList()
        if (friendResult.code === 200) {
          this.addLog(`✅ 获取好友列表成功，共${friendResult.data.length}个好友`, "success");
          friendResult.data.forEach(friend => {
            this.addLog(`好友: ${friend.username} (${friend.nickname})`, "info");
          });
        } else {
          this.addLog(`❌ 获取好友列表失败: ${friendResult.message}`, "error");
        }

        // 测试获取好友申请
        const requestResult = await getReceivedFriendRequests()
        if (requestResult.code === 200) {
          this.addLog(`✅ 获取好友申请成功，共${requestResult.data.length}个申请`, "success");
        } else {
          this.addLog(`❌ 获取好友申请失败: ${requestResult.message}`, "error");
        }

      } catch (error) {
        this.addLog(`❌ 好友管理API测试失败: ${error.message}`, "error");
      }
    },

    async testSearchUsers() {
      this.addLog("开始测试搜索用户...", "info");

      try {
        const result = await searchUsers('test')
        if (result.code === 200) {
          this.addLog(`✅ 搜索用户成功，找到${result.data.length}个用户`, "success");
          result.data.forEach(user => {
            this.addLog(`用户: ${user.username} (${user.nickname})`, "info");
          });
        } else {
          this.addLog(`❌ 搜索用户失败: ${result.message}`, "error");
        }
      } catch (error) {
        this.addLog(`❌ 搜索用户失败: ${error.message}`, "error");
      }
    },

    async testFriendRequest() {
      this.addLog("开始测试好友申请...", "info");

      try {
        // 先获取用户列表，找一个用户发送申请
        const userResult = await getUserList()
        if (userResult.code === 200 && userResult.data.length > 0) {
          const targetUser = userResult.data[0]
          
          const result = await sendFriendRequest({
            toUserId: targetUser.userId,
            message: '测试好友申请'
          })
          
          if (result.code === 200) {
            this.addLog(`✅ 发送好友申请成功`, "success");
          } else {
            this.addLog(`❌ 发送好友申请失败: ${result.message}`, "error");
          }
        } else {
          this.addLog(`❌ 无法获取用户列表进行测试`, "error");
        }
      } catch (error) {
        this.addLog(`❌ 好友申请测试失败: ${error.message}`, "error");
      }
    },
  },
};
</script>

<style scoped>
.test-container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.test-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.test-section {
  background: white;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.status-label {
  font-size: 28rpx;
  color: #666;
}

.status-value {
  font-size: 28rpx;
  font-weight: bold;
}

.status-value.success {
  color: #07c160;
}

.status-value.error {
  color: #fa5151;
}

.test-btn {
  width: 100%;
  height: 80rpx;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.test-btn:active {
  background: #0056cc;
}

.log-container {
  height: 400rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 10rpx;
  padding: 20rpx;
  background: #fafafa;
}

.log-item {
  margin-bottom: 15rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #eee;
}

.log-time {
  font-size: 22rpx;
  color: #999;
  display: block;
  margin-bottom: 5rpx;
}

.log-message {
  font-size: 26rpx;
  line-height: 1.4;
}

.log-message.info {
  color: #333;
}

.log-message.success {
  color: #07c160;
}

.log-message.error {
  color: #fa5151;
}
</style>
